////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Noo team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.cpms.controller;

import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.cpms.dto.ProjectInformation;
import com.iflytek.ci.cpms.service.ProjectService;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.framework.web.messages.AjaxMessage;
import com.iflytek.ci.cums.service.AccountService;
import com.iflytek.ci.cums.service.TeamService;
import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.main.dto.AccountValue;
import com.iflytek.ci.main.dto.CommboValue;
import com.iflytek.ci.main.dto.Macro;
import com.iflytek.ci.qams.domain.Issue;
import com.iflytek.ci.qams.domain.IssueType;
import com.iflytek.ci.qams.dto.TeamPickList;
import com.iflytek.ci.qams.service.IssueService;
import com.iflytek.ci.qams.service.TypeService;
import com.iflytek.framework.mapper.JsonMapper;
import com.iflytek.framework.web.mvc.PaginationParam;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 项目信息维护管理控制器.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-10-30 3:34 PM
 * @since JDK 1.5
 */
@Controller
@RequestMapping("project/**")
public class ProjectController extends BaseController {
    /** 序列化ID */
    private static final long serialVersionUID = 1471654642752066253L;
    /** Project服务接口 */
    @Autowired
    private ProjectService projectService;
    /** 对象包装服务 */
    @Autowired
    private Mapper mapper;
    /** 用户服务 */
    @Autowired
    private AccountService accountService;
    /** 团队服务 */
    @Autowired
    private TeamService teamService;
    /**反馈问题服务*/
    @Autowired
    private IssueService issueService;
    /**问题类型服务*/
    @Autowired
    private TypeService typeService;

//    private long projectId;
//
//
//    public long getProjectId() {
//        return projectId;
//    }
//
//    public void setProjectId(long projectId) {
//        this.projectId = projectId;
//    }

    /**
     * 跳转到project管理界面
     *
     * @return project list界面
     */
    @RequiresPermissions("project:list")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list() {
        return "project/list";
    }


    /**
     * 请求所有负责人列表
     * @return  负责人列表
     */
    @RequestMapping("all_leaders")
    @ResponseBody
    public List<AccountValue> all_leaders() {

        List<Account> tempAllLeaders = accountService.allLeaders();
        List<AccountValue> allLeaders = new ArrayList<AccountValue>();
        for (Account account : tempAllLeaders) {
            AccountValue accountValue = new AccountValue();
            mapper.map(account, accountValue);
            allLeaders.add(accountValue);
        }
        return allLeaders;
    }

    /**
     * 跳转到编辑或者新增界面，以ID为标志，如果id传递的是0，则表示新增
     *
     * @param id
     *            项目ID
     * @param model
     *            UI模型
     * @return 编辑界面
     */
    @RequiresPermissions("project:list")
    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") int id, Model model) {
        Project project;
        if (id == 0) {
            logger.info("create new project");
            project = new Project();
        } else {
            logger.info("edit a project");
            project = projectService.fromId(id);
        }
        model.addAttribute("project", project);
        model.addAttribute("id", id);
        String teamNames = "";
        String teamAccount = "";
        ArrayList<TeamPickList> allTeamAccoutList = new ArrayList<TeamPickList>();
        List<Account> accounts = accountService.get_all();
        // todo 后期数据量大的情况有必要考虑优化
        // 把所有账户传给allTeamAccoutList 这个list ，并初始化selected标记为false
        for (Account account : accounts) {
            TeamPickList tempTeamPickList = new TeamPickList();
            tempTeamPickList.setSelected(false);
            tempTeamPickList.setValue(account.getId());
            tempTeamPickList.setLabel(account.getName());
            allTeamAccoutList.add(tempTeamPickList);
        }

        List<Account> rightTeamAccout = teamService.get_unameby_tid(project
                .getTeam());
        if (project.getTeam() != 0) {
            for (int k = 0; k < rightTeamAccout.size(); k++) {
                teamNames += (rightTeamAccout.get(k).getName() + ((k == rightTeamAccout
                        .size() - 1) ? " " : Macro.COMMA));
                teamAccount += (rightTeamAccout.get(k).getId() + ((k == rightTeamAccout
                        .size() - 1) ? "" : Macro.COMMA));
            }
        }
        // 设置存在这个项目中的user selected标签为true
        for (TeamPickList anAllTeamAccoutList : allTeamAccoutList) {
            for (Account aRightTeamAccout : rightTeamAccout) {
                if (Objects.equal(anAllTeamAccoutList.getValue(),
                        aRightTeamAccout.getId())) {
                    anAllTeamAccoutList.setSelected(true);
                }
            }
        }
        model.addAttribute("teamAccout_json", JsonMapper.nonDefaultMapper()
                .toJson(allTeamAccoutList));
        model.addAttribute("teamNames", teamNames);
        model.addAttribute("teamAccount", teamAccount);
//        projectId = id;
        return "project/edit";
    }

    // ~ Start ajax response
    // ////////////////////////////////////////////////////////////////

    /**
     * 保存项目信息(包含新增或者编辑）
     *
     * @param project
     *            项目信息
     * @param result
     *            校验结果
     * @return ajax信息
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage save(@Valid Project project, BindingResult result,
                            String teamAccount, HttpServletRequest request) {
        if (result.hasErrors()) {
            return ajax_error("数据校验不正确", result.getAllErrors());
        }
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("name", project.getName());
            Project projectExit = projectService.fromKey(project.getCode());

            if (Objects.equal(project, null)) {
                ajax_error("项目信息不能为空");
            } else {
                String basePath=get_base_path(request);
                String  realPath = get_real_path(request);
                long[] team_account_ids;
                if (!Strings.isNullOrEmpty(teamAccount)) {
                    String[] team_accounts = teamAccount.split(Macro.COMMA);
                    team_account_ids = new long[team_accounts.length];
                    for (int i = 0; i < team_accounts.length; i++) {
                        String team_account = team_accounts[i];
                        team_account_ids[i] = Long.valueOf(team_account);
                    }
                } else {
                    team_account_ids = new long[0];
                }
                if (project.getId() == 0) {
                    if(projectExit !=null){
                        return AjaxMessage.instance(AjaxMessage.ERROR,
                                "该项目缩写已存在");
                    }
                    projectService.add_project(project, team_account_ids,
                            basePath,realPath);
                } else {
                    if (projectExit == null) {
                        projectService
                                .update_project(project, team_account_ids);
                    } else {
                        if (projectExit.getId() == project.getId()) {
                            projectService.update_project(project,
                                    team_account_ids);
                        } else {
                            return AjaxMessage.instance(AjaxMessage.ERROR,
                                    "该项目缩写已存在");
                        }
                    }
                }
            }
            return ajax_info("数据保存成功");
        } catch (Exception e) {
            logger.error("保存项目信息失败!", e);
            return AjaxMessage.instance(AjaxMessage.ERROR, "保存失败");
        }

    }
       //todo
//    /**
//     * 项目详细信息管理
//     * 里程碑管理 团队管理等
//     */
//    @RequestMapping("moreinfo")
//    public String  projectMore(Model model){
//        model.addAttribute("projectInfo",projectService.getProjectInformation(projectId));
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("name","mileston");
//        try {
//            milestoneService.milestones_advanced_query(projectId,params);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "project/detail";
//    }

    /**
     * 删除1个或者多个项目信息
     *
     * @param ids
     *            帐号，以逗号分割
     * @return 是否成功
     */
    @RequiresRoles("Admin")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage delete(String ids) {
        if (Strings.isNullOrEmpty(ids)) {
            return ajax_error("删除项目的ID不能为空");
        }
        String[] id_array = ids.split(Macro.COMMA);
        if (projectService.remove_project(id_array)) {
            return ajax_info("删除成功");
        } else {
            return ajax_error("项目已反馈，无法删除！");
        }
    }

    /**
     * 分页获取项目信息
     *
     * @param criteria
     *            分页参数信息
     * @return 帐号信息
     */
    @RequestMapping("list.json")
    @ResponseBody
    public PaginationResult<Project> all_projects(
            @PaginationParam(required = false) PaginationCriteria criteria) {
        return projectService.find_project(criteria);
    }

    /**
     * 根据项目名称或者项目的KEY来检索获取项目信息
     *
     * @param criteria
     *            分页参数信息
     * @param params
     *            参数信息，需要以JSON格式
     * @return 帐号信息
     */
    @RequestMapping("search")
    @ResponseBody
    public PaginationResult<Project> search_projects(
            @PaginationParam(required = false) PaginationCriteria criteria,
            @RequestBody Map<String, Object> params) {
        return projectService.search_project(criteria, params);
    }

    /**
     * 根据项目ID 获取项目的基本信息、团队信息、里程碑信息
     * @param
     */
    @RequestMapping("projectinfo/{pid}")
    @ResponseBody
    public ProjectInformation getProjectInformation(@PathVariable long pid, Model model){
        return projectService.getProjectInformation(pid);
    }
    /**
     *
     */
    @RequestMapping("fuzzy_search")
    @ResponseBody
    public PaginationResult<Project> fuzzySearchProjects(
            @PaginationParam(required = false) PaginationCriteria criteria,
            String search) {

        return projectService.fuzzySearchProjects(criteria, search);
    }

    /**
     * 检索某个项目信息
     *
     * @param id
     *            分页参数信息
     * @return 帐号信息
     */
    @RequiresRoles("Admin")
    @RequestMapping("find/{id}")
    @ResponseBody
    public Project find_projects(@PathVariable long id) {
        return projectService.fromId(id);
    }

    /**
     * 获取所有项目的id和name，并作为commbo对象返回给commbo使用。
     *
     * @return 项目Commbo
     */
    @RequestMapping("all")
    @ResponseBody
    public List<CommboValue> project_commbo() {
        List<Project> projects = projectService.all_projects();
        List<CommboValue> commboValues = Lists.newArrayList();
        CommboValue commboValue;
        for (Project project : projects) {
            commboValue = new CommboValue();
            mapper.map(project, commboValue);
            commboValues.add(commboValue);
        }
        return commboValues;
    }

    @RequestMapping("shiro")
    @ResponseBody
    public String project_user() {
        // ShiroDbRealm.ShiroUser shiro = (ShiroDbRealm.ShiroUser)
        // SecurityUtils.getSubject().getPrincipal();
        String role = "";
        if (SecurityUtils.getSubject().hasRole("Admin")) {
             role = "Admin";
        } else if (SecurityUtils.getSubject().hasRole("Leader")) {
             role = "Leader";
        } else {
             role = "User";
        }
        return role;
    }
    /**
     * 导入团队请求
     *
     * @param attachment
     *            上传的文件
     * @return ajax请求
     */
    @RequestMapping(value = "account_import", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage import_account(@RequestParam(value="pid")String pid, @RequestParam(value = "attachment") MultipartFile attachment) {
        if (!attachment.isEmpty()) {
            String file_name = attachment.getOriginalFilename();
            if (file_name.endsWith("xls")) {
                long intPid= Long.parseLong(pid);
                try{
                    projectService.import_account(intPid,attachment);
                    return ajax_info("文件导入成功！");
                }
                catch(Exception e)
                {
                    return ajax_info("文件导入失败！可能是导入的Excel文件第八列无有效邮箱数据或有用户不存在或Excel版本不对");
                }
            } else {
                return ajax_warn("请您上传Excel-2003或以下版本文件！");
            }
        } else {
            return ajax_error("请您上传Excel文件！");
        }
    }

    /**
     *  转到project首页
     *
     * @param p_key    项目p_key
     * @param model
     * @return
     */
    @RequestMapping(value = "p_dashboard/{p_key}", method = RequestMethod.GET)
    public String project_dashboard(@PathVariable("p_key") String p_key,Model model){

        long projectId = projectService.fromKey(p_key).getId();
        ProjectInformation projectInformation = projectService.getProjectInformation(projectId);
        Project project = projectInformation.getProject();
        List <Account> accountList = projectInformation.getAccounts();
        List <String> leader= accountService.get_names(new String[]{project.getLead()});
        //得到数据库type表中所有的type
        List <IssueType> typeList=  typeService.all_types();
        List <Issue> issueList = issueService.get_issue_project_order(projectId);
        for(Issue issue:issueList){
            for(IssueType issueType:typeList){
                if(issue.getIssuetype()==issueType.getId()){
                    issue.setDescription(issueType.getPname());
                }
            }
        }
        model.addAttribute("project",project);
        model.addAttribute("leader",leader);
        model.addAttribute("accounts",accountList);
        model.addAttribute("issues",issueList);
        return "project/p_dashboard";
    }
    

}
